package com.ztgf.search.server.service;

import com.ztgf.search.server.config.YmlConfig;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.ztgf.search.mapper.SearchIndexMapper;
import com.ztgf.search.models.service.ISearchIndexService;
import com.ztgf.search.models.bo.SearchIndexSaveBO;
import com.ztgf.search.models.dto.SearchIndexDTO;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 搜索引擎索引表控制器
 *
 * @author chenyu.wang
 * @Date 2021-01-28 18:13:28
 */
@DubboService
public class SearchIndexServiceImpl extends ServiceImpl<SearchIndexMapper, SearchIndexDTO> implements ISearchIndexService {

    @Resource
    private YmlConfig ymlConfig;
    @Autowired
    private ElasticsearchServiceImpl elasticsearchService;

    @Override
    public boolean add(SearchIndexSaveBO saveBO) {
        SearchIndexDTO dto = new SearchIndexDTO();
        BeanUtils.copyProperties(saveBO, dto);
        Long id = ymlConfig.getPkId();
        dto.setId(id);
        boolean insert = this.insert(dto);
        if (!insert) {
            return false;
        }
        // 创建es索引
        elasticsearchService.createIndex(saveBO.getIndexName(), saveBO.getIndexName(), 1, 1);
        return true;
    }

    @Override
    public boolean delete(Long id) {
        SearchIndexDTO indexDTO = this.selectById(id);
        if (indexDTO == null) {
            return false;
        }
        // 删除索引
        elasticsearchService.deleteIndex(indexDTO.getIndexName());
        return this.deleteById(id);
    }
}
